from django.urls import path
from django.conf import settings
from django.db import transaction

from oracle.base.baseview import render_handler
from gideon.service.starlabs import GideonHandler
from supergirl.models import ConsultRecord, Customer


class PublicCustomerHandler(GideonHandler):
    display_list = ["checkbox", "name", "qq", "class_status", "gender", "source", "education", "graduation_school",
                    "major", "experience", "work_status", "company", "record"]

    def action_multi_apply(self, title=False, url=None, data=None, *args, **kwargs):
        """
        批量申请公户用户到私户账户中来
        :param title: 显示标题标志
        :param url: 返回成功跳转的url
        :param data:
        :param args:
        :param kwargs:
        :return:
        """
        if data is None:
            data = dict()
        # 不考虑多用户的情况
        current_user_id = self.request.session.get("oracle_users_list")
        if current_user_id:
            current_user_id = current_user_id[0]["id"]
        else:
            return None
        if title:
            return '批量申请到私户中'
        else:
            # 选择客户的key的列表
            key_list = self.request.POST.getlist('key')
            private_customer_count = Customer.objects.filter(consultant_id=current_user_id, class_status=2).count()

            if not url:
                url = self.request.get_full_path()
            status = "success"
            data.update(
                {
                    "head_title": "批量申请成功",
                    "title": "批量申请公户用户到私户中成功",
                    "href": url,
                    "button_text": "返回列表页"
                }
            )

            if (private_customer_count + len(key_list)) > self.model_class.MAX_PRIVATE_CUSTOM_COUNT:
                # 限制每人拥有的私户最多为 Custom.MAX_PRIVATE_CUSTOM_COUNT 个
                data.update(
                    {
                        "head_title": "批量申请失败",
                        "title": "做人不要太贪心哦！",
                        "href": url,
                        "button_text": "返回列表页"
                    }
                )
                status = {
                    'status': 95,
                    'description': '申请了超过150人的私户账户',
                    'msg': f'做人不要太贪心，私户中已有{private_customer_count}, 最多只能申请{self.model_class.MAX_PRIVATE_CUSTOM_COUNT - private_customer_count}'
                }
            else:
                # 数据库加锁
                # 事务
                with transaction.atomic():
                    # 这一句 select_for_update 数据库加锁，相当于 select * from customer where id in [11,22] for update;
                    origin_queryset = Customer.objects.filter(
                        key__in=key_list, class_status=2, consultant__isnull=True
                    ).select_for_update()
                    if len(origin_queryset) == len(key_list):
                        origin_queryset.update(consultant_id=current_user_id)
                    else:
                        # 限制每人拥有的私户最多为 Custom.MAX_PRIVATE_CUSTOM_COUNT 个
                        data.update(
                            {
                                "head_title": "批量申请失败",
                                "title": "手速太慢了！",
                                "href": url,
                                "button_text": "返回列表页"
                            }
                        )
                        status = {
                            'status': 96,
                            'description': '选中的客户已有被其他人选中的',
                            'msg': '手速太慢了，选中的客户已有被其他人选中的，请重新选择后再试',
                        }

            return status

    def get_action_list(self, action_list=None, *args, **kwargs):
        action_list = super().get_action_list(action_list, *args, **kwargs)
        action_list.append(self.action_multi_apply)
        return action_list

    def get_extra_urls(self):
        patterns = [
            path(r'record/<slug:key>/', self.record_view, name=self.get_url_name('record_view')),
        ]
        return patterns

    def get_queryset(self, handle_type='list', *args, **kwargs):
        if handle_type == "list":
            return self.model_class.objects.filter(consultant__isnull=True)
        return super().get_queryset(handle_type, *args, **kwargs)

    def record_view(self, request, key):
        self.initialize(request)
        status = "success"
        data = {"timeline_items": []}

        queryset = ConsultRecord.objects.filter(customer__key=key)
        for item in queryset:
            url = None
            if item.link_name:
                if item.link_name.startswith("http"):
                    url = item.link_name
                else:
                    url = self.reverse_handle_url(request, item.link_name)
            data["timeline_items"].append({
                "icon": item.icon,
                "title": item.title,
                "note": item.note,
                "href": url,
                "link_title": item.link_title,
                "date": item.date.strftime("%Y-%m-%d"),
            })

        template = "supergirl/recode.html"
        return render_handler(request, status, template=template, data=data)

    def show_add_button(self, obj=None, is_header=True, *args, **kwargs):
        # gideon 控制是否显示添加按钮 (权限控制到按钮粒度，在程序中使用代码控制，控制条件更精细。使用oracle在template控制，控制更方便、快捷)
        # 当前用户所有的权限信息
        permissions = self.request.session.get(settings.PERMISSION_SESSION_KEY)
        if permissions and self.get_url_name_add() not in permissions:
            return None
        return super().show_add_button(obj, is_header, *args, **kwargs)

    def show_record_field(self, obj=None, is_title=False, *args, **kwargs):
        title = "跟进记录"
        if is_title:
            return title
        if obj:
            url = self.reverse_handle_url(self.request, self.get_url_name('record_view'), key=obj.key)
            return {"href": url, "title": title}, "body", {"type": "link"}
        return "record function error"
